
sudo rm -rf /data/chrootubuntu
mkdir /data/chrootubuntu
cd /data/chrootubuntu
wget -O busybox https://www.busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-armv8l
chmod +x busybox
BUSYBOXPATH="$PWD/busybox"

cat > startubuntu22.sh << 'EOF'

#!/bin/sh

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH
export HOME=/root

# Ubuntu档案系统所在路径
UBUNTUPATH="/data/chrootubuntu/ubuntu22"
# 解决setuid问题
sudo mount -o remount,dev,suid /data

#挂载目录
sudo mount --bind /dev $UBUNTUPATH/dev
sudo mount --bind /sys $UBUNTUPATH/sys
sudo mount --bind /proc $UBUNTUPATH/proc
sudo mount -t devpts devpts $UBUNTUPATH/dev/pts
# 掛载內部储存空间
sudo mount --bind /sdcard $UBUNTUPATH/sdcard

test $# -eq 0 && set -- /bin/bash -l

# chroot至Ubuntu
sudo chroot $UBUNTUPATH serviced

#卸载挂载目录
sudo umount $UBUNTUPATH/dev/pts
sudo umount $UBUNTUPATH/dev
sudo umount $UBUNTUPATH/proc
sudo umount $UBUNTUPATH/sys
sudo umount $UBUNTUPATH/sdcard


EOF
chmod +x startubuntu22.sh


mkdir ubuntu22
cd ubuntu22

#下载最新Ubuntu 22.04 base档案系统
wget https://mirrors.tuna.tsinghua.edu.cn/ubuntu-cdimage/ubuntu-base/releases/22.04.4/release/ubuntu-base-22.04-base-arm64.tar.gz
tar xpvf ubuntu-base-22.04-base-arm64.tar.gz --numeric-owner
rm ubuntu-base-22.04-base-arm64.tar.gz

#修正DNS和新增本機名稱
echo "nameserver 223.5.5.5" > etc/resolv.conf
echo "127.0.0.1 localhost" > etc/hosts

#默认使用bash
sed -i 's/^SHELL=.*/SHELL=\/bin\/bash/' "etc/default/useradd"

#使用国内镜像
rm etc/apt/sources.list
cat > etc/apt/sources.list << 'EOF'

# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy main restricted universe multiverse
# deb-src http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy main restricted universe multiverse
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-updates main restricted universe multiverse
# deb-src http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-updates main restricted universe multiverse
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-backports main restricted universe multiverse
# deb-src http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-backports main restricted universe multiverse

# 以下安全更新软件源包含了官方源与镜像站配置，如有需要可自行修改注释切换
deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse
# deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse

# 预发布软件源，不建议启用
# deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-proposed main restricted universe multiverse
# # deb-src http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/ jammy-proposed main restricted universe multiverse

EOF

#chroot下的systemd问题
cat > usr/local/bin/serviced << 'EOF'

#!/bin/sh
# Control services for system based on Systemd inside chroot and SysVinit outside chroot
# https://github.com/smaknsk/servicectl
#

# Path locate this script
DIR=$(dirname $(readlink -f $0))

# Path contents symlink on systemd units files
SERVICECTL_ENABLED_PATH="$DIR/enabled/"

action="start"
if [[ -n $1 ]]; then
    action=$1
fi

servicectl $action $(dir $SERVICECTL_ENABLED_PATH)

EOF

#chroot下的systemd问题
cat > usr/local/bin/servicectl << 'EOF'

#!/bin/sh
# Control services for system based on Systemd inside chroot and SysVinit outside chroot
# https://github.com/smaknsk/servicectl
#

# Pach systemd services file
SYSTEMD_UNITS_PATH="/usr/lib/systemd/system/"

# Path locate this script
DIR=$(dirname $(readlink -f $0))

# Path contents symlink on systemd units files
SERVICECTL_ENABLED_PATH="$DIR/enabled/"

# Check is root
if [ $EUID -ne 0 ]; then
  echo "You must run as root user" 2>&1
  exit 1
fi

# Parse ini file. usage: parse $inifile $section $key
# Return 0 on success, 1 if file cannot be opened, 2 if the given key cannot be found in the given section
function parse()
{
  local _inifile=$1
  local _section=$2
  local _key=$3

   if [ ! -r "$_inifile" ]
   then
     exit 1;
   fi        

   exec < $_inifile

   while read section; do
     if [ "$section" = '['$_section']' ] ; then
       IFS='='
       while read key value; do
         # check if we are still within our section
         if [ `echo -n $key | grep "^\s*\[.*\]\s*$"` ]; then
            exit 2;
         fi
         # strip leading and trailing whitespace from keys
         key=`echo -n "$key" | sed 's/^\s*//;s/\s*$//'`
         _key=`echo -n "$_key" | sed 's/^\s*//;s/\s*$//'`
         if [ "$key" = "$_key" ]; then
           echo $value
           exit 0;
         fi
      done
    fi
  done
  exit 2;
}

# Execute action from systemd service file
function exec_action() {
    local action=$1
    local service=$2
    local file="${SYSTEMD_UNITS_PATH}${service}.service"
    local is_required=1 # by default turn action is required
    local cmd=""
        
    # if passed arg $3 then set value
    if [[ -n $3 ]]; then
        local is_required=$3
    fi

    cmd=`parse $file Service $action`
    local ret=$?    
    if [ $ret = 1 ]; then
        echo "Error: file $file cannot be opened"
        return 1
    fi
    if [ $ret = 2 ]; then
    
        # if action required, return error
        if [ $is_required = 1 ]; then
            echo "Error: action $action not found in file $file"
            return 1
        fi
        
        return 0        
    fi
  
    eval $cmd
    return $?
}

function exec_if_exists() {
    exec_action $@ 0
}

function exec_stop() {
    local service=$1
    local file="${SYSTEMD_UNITS_PATH}${service}.service"
    local cmd=""
    
    cmd=`parse $file Service ExecStop`
    local ret=$?
    
    # if ExecStop exists
    if [ $ret = 0 ]; then
        exec_action ExecStop $service
        return $?
    fi
    
    # get path pid file
    pid_file=`parse $file Service PIDFile`
    local ret=$?
    if [ $ret != 0 ]; then
        echo "Error: attribute PIDFile not exists in file $file"
        return 1
    fi

    read PID < $pid_file
    kill -TERM "$PID" || echo "Couldn't kill PID"
}

if [[ -z ${@:2} ]]; then
    echo "Error: you must specify the service"
    exit 1
fi

# Switch action
case "$1" in
    start)
        for service in ${@:2} 
        do
            service=${service%".service"}
            exec_if_exists ExecStartPre $service
            if [ $? = 0 ]; then
                exec_action ExecStart $service
            fi
        done
    ;;
    
    stop)
        for service in ${@:2} 
        do
            service=${service%".service"}
            exec_stop $service
        done
    ;;
    
    restart)
        for service in ${@:2} 
        do
            service=${service%".service"}
            exec_stop $service
            exec_action ExecStart $service
        done
    ;;
    
    reload)
        for service in ${@:2} 
        do
            service=${service%".service"}
            exec_action ExecReload $service
        done
    ;;

    enable)
        for service in ${@:2} 
        do
            service=${service%".service"}
            file="${SYSTEMD_UNITS_PATH}${service}.service"
            enabled_symlink="${SERVICECTL_ENABLED_PATH}${service}.service"

            if [ ! -f "$file" ]; then
                echo "Error: file $file is not exists"
                continue
            fi

            if [ -f "$enabled_symlink" ]; then
                echo "${service} already enabled"
                continue
            fi

            echo "ln -s \"$file\" \"$enabled_symlink\""
            ln -s "$file" "$enabled_symlink"
        done
    ;;

    disable)
        for service in ${@:2} 
        do
            service=${service%".service"}
            file="${SERVICECTL_ENABLED_PATH}${service}.service"
            if [ ! -f "$file" ]; then
                echo "Error: file $file is not exists"
                continue
            fi
            
            echo "rm $file"
            rm $file
        done
    ;;
    
    *)
        echo "Availble action: start, stop, restart, reload, enable or disable"
        exit 1
    ;;
esac

EOF

chmod +x usr/local/bin/servicectl
chmod +x usr/local/bin/serviced 
mkdir usr/local/bin/enabled
#修复环境问题
cat > fix_install.sh << 'EOF'
#!/bin/sh

#修复网络问题
groupadd -g 3003 aid_inet
groupadd -g 3004 aid_net_raw
groupadd -g 1003 aid_graphics
usermod -g 3003 -G 3003,3004 -a _apt
usermod -G 3003 -a root

#设定时区为上海
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

#安裝常用工具

apt update
apt upgrade -y
apt install vim net-tools sudo git openssh-server -y

rm /bin/sh
ln -s /bin/bash /bin/sh

mkdir /run/sshd
servicectl enable ssh

#创建普通用户
adduser --quiet jincs

EOF
chmod +x fix_install.sh

mkdir sdcard

cd ../

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH
export HOME=/root

# Ubuntu档案系统所在路径
UBUNTUPATH="/data/chrootubuntu/ubuntu22"
# 解决setuid问题
sudo mount -o remount,dev,suid /data

#挂载目录
sudo mount --bind /dev $UBUNTUPATH/dev
sudo mount --bind /sys $UBUNTUPATH/sys
sudo mount --bind /proc $UBUNTUPATH/proc
sudo mount -t devpts devpts $UBUNTUPATH/dev/pts
# 掛载內部储存空间
sudo mount --bind /sdcard $UBUNTUPATH/sdcard

test $# -eq 0 && set -- /bin/bash -l

# chroot至Ubuntu
sudo chroot $UBUNTUPATH /fix_install.sh

#卸载挂载目录
sudo umount $UBUNTUPATH/dev/pts
sudo umount $UBUNTUPATH/dev
sudo umount $UBUNTUPATH/proc
sudo umount $UBUNTUPATH/sys
sudo umount $UBUNTUPATH/sdcard
rm $UBUNTUPATH/fix_install.sh

echo "安装ubuntu22成功，执行 sh /data/chrootubuntu/startubuntu22.sh & 启动系统"
echo "并使用刚才的用户通过ssh登录"



